package com.nuc.kl.module.kpoint.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.nuc.kl.base.DaoSupportImpl;
import com.nuc.kl.module.kpoint.dao.KnowledgeCheckDao;
import com.nuc.kl.module.kpoint.entity.Knowledge;
import com.nuc.kl.module.kpoint.entity.KnowledgeCheck;
import com.nuc.kl.module.kpoint.service.KPointService;
import com.nuc.kl.module.kpoint.service.KnowledgeCheckService;
import com.nuc.kl.module.usermanager.entity.People;

@Service
@Transactional
public class KnowledgeCheckServiceImpl extends DaoSupportImpl<KnowledgeCheck>
		implements KnowledgeCheckService {

	@Resource
	private KnowledgeCheckDao knowledgeCheckDao;
	@Resource
	private KPointService kpointService;
	private Float rate;
	private People people;

	/**
	 * 审核知识点
	 */
	public void check(Knowledge model, String view, People people) {
		this.people = people;
		KnowledgeCheck knowledgeCheck = new KnowledgeCheck();
		knowledgeCheck.setKnowledge(model);
		knowledgeCheck.setPeople(people);
		knowledgeCheck.setView(view);
		save(knowledgeCheck);
		count(model.getId());

	}

	// 计算审核是否通过既定的规则
	public void count(Long id) {

		Properties properties = new Properties();
		// InputStream is =
		// getClass().getResourceAsStream("/knowledgeCheck.properties");
		InputStream is;
		try {
			is = new FileInputStream(ServletActionContext.getServletContext()
					.getRealPath("/WEB-INF/classes")
					+ File.separator + "knowledgeCheck.properties");
			properties.load(is);
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		Knowledge knowledge = kpointService.getById(id);
		Set<KnowledgeCheck> kcs = knowledge.getKnowledgeCheck();
		if (kcs.size() >= Integer.parseInt(properties.getProperty("checknum"))) {

			rate = this.getCheckTrueNum(knowledge)
					/ Float.parseFloat(kcs.size() + "");

			if ((rate * 100) >= (Integer.parseInt(properties
					.getProperty("passrate")))) {
				knowledge.setStatus(0);
				kpointService.updateStatus(knowledge, people);
				this.clearByKnowledge(knowledge);
			} else {
				knowledge.setStatus(3);
				kpointService.updateStatus(knowledge, people);
				this.clearByKnowledge(knowledge);
			}
		}

	}

	public void clearByKnowledge(Knowledge knowledge) {

		knowledgeCheckDao.deleteByKnowledge(knowledge);
	}

	public int getCheckTrueNum(Knowledge knowledge) {

		return knowledgeCheckDao.getCheckTrueNum(knowledge);
	}

}
